function getMessages(msgBox){
	$('#msgNav td').removeClass('active');
	$('#' + msgBox + 'Msg').addClass('active');
	$.get (
		'getMessages?set_ajax_view',
		{
			whichbox: msgBox
		},
		function(data) {
			$('#newMessageForm').hide();
			$('#messageContent').hide();
			$('#allMessages').html(data);	
			$('#allMessages').show();
			$("#imgtip span.uName").tooltip({ 
				top: -210,
				left: -20,
				opacity: 10,
			    bodyHandler: function() { 
					return $("<img/>").attr('src', $(this).parent('td').children('img').attr('src'));  
			    }, 
			    showURL: false 
			});
			getNumOfNewMessages();
			$("#checkall").click(function() { 
				var checked_status = this.checked; 
			    $("input").each(function() { 
			    	this.checked = checked_status; 
			    }); 
			});
		}
	);	
}

function getFavourite(){
	$('#msgNav td').removeClass('active');
	$('#favourite').addClass('active');
	$.get (
		'getFavourite?set_ajax_view',
		{},
		function(data) {
			$('#newMessageForm').hide();
			$('#allMessages').html(data);
			$("div.scrollable").scrollable({
				size: 4,
				speed: 100
			});
			$('#allMessages').show();
		}
	);
}

function displayNewMessage(){
	$.get (
		'getFavouriteToAdd?set_ajax_view',
		{},
		function(data) {
			$('#favouriteListSection').html(data);
		}
	)
	$('#msgNav td').removeClass('active');
	$('#newMsg').addClass('active');
	$('#allMessages').hide();
	$('#messageContent').hide();
	$('#newMessageForm').show();
	$('#send_message_errors').html('');
}

function deleteMessages(whichbox){
	var idArray = new Array();
    $("#messages tr td input:checked").each(function(id) {
   		var message = $("#messages tr td input:checked").get(id);
   		idArray.push(message.value);
    });
    if (idArray.length < 1) {
    	return;
    }
	$.get (
		'deleteMessages?set_ajax_view',
		{
			whichbox: whichbox,
			'deleted[]': idArray
		},
		function(data){
			var obj = data;
			for (var i=0; i<obj.length; i++) {			
	   			$('tr#' + obj[i]).remove();
	   		}
			$('table#messages tr:even').addClass('alt');
			if (whichbox == 'inbox') {
				getNumOfNewMessages();
			}
			$('input#checkall').removeAttr('checked');
	   	},
	   	"json"
   	);
}

function cancelMessage(){	
	getMessages('inbox');
}

function sendMessage(){
	// Check for correct information
	var recipients = $('#recipients').val();
	recipients = recipients.split(' ').join('');
	recipients = recipients.split(';').join('');
	if (recipients != ""){
		$.post (
			'checkRecipients?set_ajax_view',
			{
				recipients: document.getElementById('recipients').value
			},
			function(data) {	
				if (data == "OK"){		
					$.post (
						'sendMessage?set_ajax_view',
						{
							recipientList: $('#recipients').val(),
							message: $('#message').val(),
							emergency: $('#emergency:checked').val()
						},
						function(data) {
							getMessages('outbox');
							$('#send_message_errors').html('');
							$('#recipients').val('');
							$('#message').val('');
							$('#emergency').removeAttr('checked');
						}
					);
				} else {
					$('#send_message_errors').html("<font color='red'>" + _("Account {0} doesn't exist!",data) + "</font>");
				}
			}
		);	
			
	} else {
		$('#send_message_errors').html("<font color='red'>" + _("Invalid account name") + "</font>");
	}
}

function getNumOfNewMessages(){
	$.get (
		'getNumOfNewMessages?set_ajax_view',
		{},
		function (data){
			if (data > 0) {
				$('#newMsgWarning').html(data);
				$('div.msgWarning').show();				
			} else {
				$('div.msgWarning').hide();
			}
		}, "json");
}

function viewMessage(messageId, rootId, username, box) {
	if (box == 'inbox' && $('tr#' + messageId + ' td:eq(2)').html() != '&nbsp;') {
		$.get (
			'markAsRead?set_ajax_view',
			{
				messageId: messageId
			},
			function (data){
				getNumOfNewMessages();
			});
	}
	$.get (
		'viewConversation?set_ajax_view',
		{
			messageId: messageId,
			rootId: rootId,
			username: username
		},
		function (data){
			$('#messageContent').html(data);
			$('#allMessages').hide();
			$('#messageContent').show();
		});
}

function addFavourite(userId, username) {
	var countTd = $('table#favouriteList tr.itemList td.mapItem').size();
	if (countTd < 5) {
		for (i = 0; i < countTd; i++) {
			if ($('table#favouriteList tr.itemList td.mapItem:eq(' + i +') div').attr('id') == userId) {
				$('#mapError').html(_('{0} have been in list',username));
				return;
			}
		}
		$.get (
			'updateFavouriteMap?set_ajax_view',
			{
				userId: userId
			},
			function (data){
				if (data != '' && data > 0) {
					var path = $('#pathInfo').text();
					var html = "<td class='mapItem' id='" + data + "'style='width: 170px'>" +
									"<div id='" + userId + "'>" +
       									"<img src='" + path + username + ".png' />" +
       									"<table style='width: 100%'><tr>" +
       			       						"<td><span style='color: #0092BE; font-weight: bold'>" + username + "</span></td>" +
       			       						"<td style='width: 25px; cursor: pointer'><img onclick='deleteFavourite(" + data + ")' src='../images/msg_remove_favourite.png' /></td>"
       			       					"</tr></table></div></td>";
					$('table#favouriteList tr.itemList').append(html);
					$('#mapError').html('');
				} else if (data == -1){
					$('#mapError').html(_('{0} have been in list',username));
				} else {
					$('#mapError').html(_('Error with updating DB'));
				}
			});
	} else {
		$('#mapError').html(_('Maximum 5 people in the list'));
	}
	
}

function deleteFavourite(mappingId) {
	$.get (
		'deleteFavouriteMap?set_ajax_view',
		{
			mappingId: mappingId
		},
		function (data){
			if (data == true) {
				$('table#favouriteList tr.itemList td#' + mappingId).remove();
			}
		});
}

function toggleAddFavourite() {
	$('#addFavouriteUserPanel').toggle('slow');
}

function addFavouriteRecipient(username) {
	var recipients = $.trim($('#recipients').val());
	if (recipients.match(username)) {
		return;
	}
	if (recipients == '') {
		recipients += username + ';'
	} else if (recipients.charAt(recipients.length - 1) == ';') {
		recipients += ' ' + username + ';'
	} else {
		recipients += '; ' + username + ';'
	}
	$('#recipients').val(recipients);
}

function replyMessage(rootId, username, emergency) {
	$('#recipientImg').attr('src', $('#pathInfo').html() + username + ".png");
	$('#replyContent').val('');
	$('#replyRecipient').val(username);
	$('#replyEmergency').val(emergency);
	$('#replyRootId').val(rootId);
	$('#replyMsgDialog').dialog('open');
}

function sendReplyMessage() {
	$.post (
		'replyMessage?set_ajax_view',
		{
			recipient: $('#replyRecipient').val(),
			message: $('#replyContent').val(),
			emergency: $('#replyEmergency').val(),
			rootId: $('#replyRootId').val()
		},
		function(data) {
			if (data > 0) {
				$('#replyMsgDialog').dialog("close");
			}
		}
	);
}